//
//  DMLifecycleStateManager.m
//  DualMediationSDK
//
//  生命周期状态管理器实现
//

#import "DMLifecycleStateManager.h"

#pragma mark - 通知名称定义

NSNotificationName const DMLifecycleStateDidChangeNotification = @"DMLifecycleStateDidChangeNotification";
NSString * const DMLifecycleStateChangeUserInfoKeyPreviousState = @"previousState";
NSString * const DMLifecycleStateChangeUserInfoKeyCurrentState = @"currentState";
NSString * const DMLifecycleStateChangeUserInfoKeyTimestamp = @"timestamp";

#pragma mark - 状态历史记录项实现

@implementation DMLifecycleStateHistoryItem

- (NSString *)description {
    return [NSString stringWithFormat:@"<DMLifecycleStateHistoryItem: state=%@, event=%@, timestamp=%@, duration=%.2fs>",
            DMLifecycleStateDescription(self.state),
            DMLifecycleEventDescription(self.triggerEvent),
            self.timestamp,
            self.duration];
}

@end

#pragma mark - 状态管理器实现

@interface DMLifecycleStateManager ()

// 状态属性
@property (nonatomic, assign) DMLifecycleState currentState;
@property (nonatomic, assign) DMLifecycleState previousState;
@property (nonatomic, strong) NSDate *lastStateChangeTime;
@property (nonatomic, assign) BOOL isInitialized;

// 状态历史
@property (nonatomic, strong) NSMutableArray<DMLifecycleStateHistoryItem *> *stateHistory;
@property (nonatomic, assign) NSUInteger maxHistoryCount;

// 状态监听器
@property (nonatomic, strong) NSMutableDictionary<NSString *, DMLifecycleStateChangeBlock> *stateChangeListeners;

// 线程安全
@property (nonatomic, strong) dispatch_queue_t stateQueue;
@property (nonatomic, strong) dispatch_queue_t historyQueue;
@property (nonatomic, strong) dispatch_queue_t listenerQueue;

@end

@implementation DMLifecycleStateManager

static DMLifecycleStateManager *_sharedManager = nil;
static dispatch_once_t onceToken;

#pragma mark - 单例实现

+ (instancetype)sharedManager {
    dispatch_once(&onceToken, ^{
        _sharedManager = [[self alloc] init];
    });
    return _sharedManager;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        [self setupStateManager];
    }
    return self;
}

- (void)setupStateManager {
    // 创建串行队列确保线程安全
    _stateQueue = dispatch_queue_create("com.dualmediationsdk.state.manager", DISPATCH_QUEUE_SERIAL);
    _historyQueue = dispatch_queue_create("com.dualmediationsdk.state.history", DISPATCH_QUEUE_SERIAL);
    _listenerQueue = dispatch_queue_create("com.dualmediationsdk.state.listener", DISPATCH_QUEUE_SERIAL);
    
    // 初始化状态
    _currentState = DMLifecycleStateUnknown;
    _previousState = DMLifecycleStateUnknown;
    _lastStateChangeTime = [NSDate date];
    _isInitialized = NO;
    
    // 初始化历史记录
    _stateHistory = [NSMutableArray array];
    _maxHistoryCount = 100; // 默认保留最近100条记录
    
    // 初始化监听器
    _stateChangeListeners = [NSMutableDictionary dictionary];
}

#pragma mark - 状态查询

- (DMLifecycleState)getCurrentState {
    return self.currentState;
}

- (NSTimeInterval)currentStateDuration {
    __block NSTimeInterval duration = 0;
    dispatch_sync(self.stateQueue, ^{
        if (self.lastStateChangeTime) {
            duration = [[NSDate date] timeIntervalSinceDate:self.lastStateChangeTime];
        }
    });
    return duration;
}

- (BOOL)isActive {
    return self.currentState == DMLifecycleStateActive;
}

- (BOOL)isForeground {
    DMLifecycleState state = self.currentState;
    return state == DMLifecycleStateActive || state == DMLifecycleStateInactive;
}

- (BOOL)isBackground {
    return self.currentState == DMLifecycleStateBackground;
}

- (BOOL)isSuspended {
    return self.currentState == DMLifecycleStateSuspended;
}

- (BOOL)isTerminated {
    return self.currentState == DMLifecycleStateTerminated;
}

#pragma mark - 状态转换

- (BOOL)transitionToState:(DMLifecycleState)newState withEvent:(DMLifecycleEvent)event {
    __block BOOL success = NO;
    
    dispatch_sync(self.stateQueue, ^{
        // 检查状态转换是否有效
        if (![self isValidTransitionFromState:self.currentState toState:newState withEvent:event]) {
            NSLog(@"[DMLifecycleStateManager] Invalid state transition from %@ to %@ with event %@",
                  DMLifecycleStateDescription(self.currentState),
                  DMLifecycleStateDescription(newState),
                  DMLifecycleEventDescription(event));
            return;
        }
        
        [self performStateTransition:newState withEvent:event];
        success = YES;
    });
    
    return success;
}

- (BOOL)transitionToState:(DMLifecycleState)newState {
    // 根据状态自动推断事件类型
    DMLifecycleEvent event = DMLifecycleEventUnknown;
    
    switch (newState) {
        case DMLifecycleStateLaunching:
            event = DMLifecycleEventDidFinishLaunching;
            break;
        case DMLifecycleStateActive:
            event = DMLifecycleEventDidBecomeActive;
            break;
        case DMLifecycleStateInactive:
            event = DMLifecycleEventWillResignActive;
            break;
        case DMLifecycleStateBackground:
            event = DMLifecycleEventDidEnterBackground;
            break;
        case DMLifecycleStateForeground:
            event = DMLifecycleEventWillEnterForeground;
            break;
        case DMLifecycleStateTerminating:
            event = DMLifecycleEventWillTerminate;
            break;
        default:
            event = DMLifecycleEventUnknown;
            break;
    }
    
    return [self transitionToState:newState withEvent:event];
}

- (void)forceSetState:(DMLifecycleState)state withEvent:(DMLifecycleEvent)event {
    dispatch_sync(self.stateQueue, ^{
        [self performStateTransition:state withEvent:event];
    });
}

- (void)performStateTransition:(DMLifecycleState)newState withEvent:(DMLifecycleEvent)event {
    DMLifecycleState oldState = self.currentState;
    NSDate *transitionTime = [NSDate date];
    
    // 更新历史记录中上一个状态的持续时间
    if (self.stateHistory.count > 0 && self.lastStateChangeTime) {
        DMLifecycleStateHistoryItem *lastItem = self.stateHistory.lastObject;
        lastItem.duration = [transitionTime timeIntervalSinceDate:self.lastStateChangeTime];
    }
    
    // 更新状态
    self.previousState = oldState;
    self.currentState = newState;
    self.lastStateChangeTime = transitionTime;
    
    if (!self.isInitialized) {
        self.isInitialized = YES;
    }
    
    // 添加到历史记录
    [self addStateToHistory:newState withEvent:event timestamp:transitionTime];
    
    // 通知监听器
    [self notifyStateChangeListeners:oldState currentState:newState event:event timestamp:transitionTime];
    
    // 发送系统通知
    [self postStateChangeNotification:oldState currentState:newState timestamp:transitionTime];
    
    NSLog(@"[DMLifecycleStateManager] State transition: %@ -> %@ (event: %@)",
          DMLifecycleStateDescription(oldState),
          DMLifecycleStateDescription(newState),
          DMLifecycleEventDescription(event));
}

- (void)reset {
    dispatch_sync(self.stateQueue, ^{
        self.currentState = DMLifecycleStateUnknown;
        self.previousState = DMLifecycleStateUnknown;
        self.lastStateChangeTime = [NSDate date];
        self.isInitialized = NO;
    });
    
    dispatch_sync(self.historyQueue, ^{
        [self.stateHistory removeAllObjects];
    });
    
    dispatch_sync(self.listenerQueue, ^{
        [self.stateChangeListeners removeAllObjects];
    });
}

#pragma mark - 状态转换验证

- (BOOL)isValidTransitionFromState:(DMLifecycleState)fromState 
                           toState:(DMLifecycleState)toState 
                         withEvent:(DMLifecycleEvent)event {
    // 如果是第一次设置状态，允许任何转换
    if (!self.isInitialized || fromState == DMLifecycleStateUnknown) {
        return YES;
    }
    
    // 相同状态转换总是有效的
    if (fromState == toState) {
        return YES;
    }
    
    // 使用全局函数进行验证
    return DMLifecycleIsValidStateTransition(fromState, toState);
}

#pragma mark - 状态历史管理

- (void)addStateToHistory:(DMLifecycleState)state withEvent:(DMLifecycleEvent)event timestamp:(NSDate *)timestamp {
    dispatch_async(self.historyQueue, ^{
        DMLifecycleStateHistoryItem *item = [[DMLifecycleStateHistoryItem alloc] init];
        item.state = state;
        item.triggerEvent = event;
        item.timestamp = timestamp;
        item.duration = 0; // 将在下次状态转换时更新
        
        [self.stateHistory addObject:item];
        
        // 限制历史记录数量
        while (self.stateHistory.count > self.maxHistoryCount) {
            [self.stateHistory removeObjectAtIndex:0];
        }
    });
}

- (NSArray<DMLifecycleStateHistoryItem *> *)getStateHistory:(NSUInteger)limit {
    __block NSArray<DMLifecycleStateHistoryItem *> *history = nil;
    
    dispatch_sync(self.historyQueue, ^{
        if (limit == 0 || limit >= self.stateHistory.count) {
            history = [self.stateHistory copy];
        } else {
            NSRange range = NSMakeRange(self.stateHistory.count - limit, limit);
            history = [self.stateHistory subarrayWithRange:range];
        }
        
        // 按时间倒序排列
        history = [history sortedArrayUsingComparator:^NSComparisonResult(DMLifecycleStateHistoryItem *obj1, DMLifecycleStateHistoryItem *obj2) {
            return [obj2.timestamp compare:obj1.timestamp];
        }];
    });
    
    return history;
}

- (NSTimeInterval)getTotalTimeInState:(DMLifecycleState)state {
    __block NSTimeInterval totalTime = 0;
    
    dispatch_sync(self.historyQueue, ^{
        for (DMLifecycleStateHistoryItem *item in self.stateHistory) {
            if (item.state == state) {
                totalTime += item.duration;
            }
        }
        
        // 如果当前状态匹配，加上当前状态的持续时间
        if (self.currentState == state) {
            totalTime += self.currentStateDuration;
        }
    });
    
    return totalTime;
}

- (NSUInteger)getTransitionCount:(DMLifecycleState)fromState toState:(DMLifecycleState)toState {
    __block NSUInteger count = 0;
    
    dispatch_sync(self.historyQueue, ^{
        for (NSUInteger i = 1; i < self.stateHistory.count; i++) {
            DMLifecycleStateHistoryItem *previousItem = self.stateHistory[i-1];
            DMLifecycleStateHistoryItem *currentItem = self.stateHistory[i];
            
            BOOL fromMatches = (fromState == DMLifecycleStateUnknown) || (previousItem.state == fromState);
            BOOL toMatches = (toState == DMLifecycleStateUnknown) || (currentItem.state == toState);
            
            if (fromMatches && toMatches) {
                count++;
            }
        }
    });
    
    return count;
}

- (void)clearStateHistory {
    dispatch_async(self.historyQueue, ^{
        [self.stateHistory removeAllObjects];
    });
}

#pragma mark - 状态监听器管理

- (void)addStateChangeListener:(NSString *)identifier block:(DMLifecycleStateChangeBlock)block {
    if (!identifier || !block) {
        return;
    }
    
    dispatch_async(self.listenerQueue, ^{
        self.stateChangeListeners[identifier] = [block copy];
    });
}

- (void)removeStateChangeListener:(NSString *)identifier {
    if (!identifier) {
        return;
    }
    
    dispatch_async(self.listenerQueue, ^{
        [self.stateChangeListeners removeObjectForKey:identifier];
    });
}

- (void)removeAllStateChangeListeners {
    dispatch_async(self.listenerQueue, ^{
        [self.stateChangeListeners removeAllObjects];
    });
}

- (void)notifyStateChangeListeners:(DMLifecycleState)previousState 
                      currentState:(DMLifecycleState)currentState 
                             event:(DMLifecycleEvent)event 
                         timestamp:(NSDate *)timestamp {
    dispatch_async(self.listenerQueue, ^{
        for (NSString *identifier in self.stateChangeListeners) {
            DMLifecycleStateChangeBlock block = self.stateChangeListeners[identifier];
            if (block) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    block(previousState, currentState, event, timestamp);
                });
            }
        }
    });
}

- (void)postStateChangeNotification:(DMLifecycleState)previousState 
                       currentState:(DMLifecycleState)currentState 
                          timestamp:(NSDate *)timestamp {
    NSDictionary *userInfo = @{
        DMLifecycleStateChangeUserInfoKeyPreviousState: @(previousState),
        DMLifecycleStateChangeUserInfoKeyCurrentState: @(currentState),
        DMLifecycleStateChangeUserInfoKeyTimestamp: timestamp
    };
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [[NSNotificationCenter defaultCenter] postNotificationName:DMLifecycleStateDidChangeNotification
                                                            object:self
                                                          userInfo:userInfo];
    });
}

#pragma mark - 调试和诊断

- (NSDictionary *)getDebugInfo {
    __block NSDictionary *debugInfo = nil;
    
    dispatch_sync(self.stateQueue, ^{
        debugInfo = @{
            @"currentState": DMLifecycleStateDescription(self.currentState),
            @"previousState": DMLifecycleStateDescription(self.previousState),
            @"lastStateChangeTime": self.lastStateChangeTime ?: [NSNull null],
            @"currentStateDuration": @(self.currentStateDuration),
            @"isInitialized": @(self.isInitialized),
            @"historyCount": @(self.stateHistory.count),
            @"maxHistoryCount": @(self.maxHistoryCount),
            @"listenerCount": @(self.stateChangeListeners.count)
        };
    });
    
    return debugInfo;
}

- (BOOL)validateInternalConsistency {
    __block BOOL isConsistent = YES;
    
    dispatch_sync(self.stateQueue, ^{
        // 检查状态是否有效
        if (self.currentState < DMLifecycleStateUnknown || self.currentState > DMLifecycleStateTerminated) {
            NSLog(@"[DMLifecycleStateManager] Invalid current state: %ld", (long)self.currentState);
            isConsistent = NO;
        }
        
        if (self.previousState < DMLifecycleStateUnknown || self.previousState > DMLifecycleStateTerminated) {
            NSLog(@"[DMLifecycleStateManager] Invalid previous state: %ld", (long)self.previousState);
            isConsistent = NO;
        }
        
        // 检查时间戳
        if (self.isInitialized && !self.lastStateChangeTime) {
            NSLog(@"[DMLifecycleStateManager] Missing last state change time");
            isConsistent = NO;
        }
    });
    
    dispatch_sync(self.historyQueue, ^{
        // 检查历史记录的时间顺序
        for (NSUInteger i = 1; i < self.stateHistory.count; i++) {
            DMLifecycleStateHistoryItem *previous = self.stateHistory[i-1];
            DMLifecycleStateHistoryItem *current = self.stateHistory[i];
            
            if ([current.timestamp compare:previous.timestamp] == NSOrderedAscending) {
                NSLog(@"[DMLifecycleStateManager] History timestamps out of order at index %lu", (unsigned long)i);
                isConsistent = NO;
            }
        }
    });
    
    return isConsistent;
}

- (nullable NSString *)exportStateHistoryAsJSON {
    __block NSString *jsonString = nil;
    
    dispatch_sync(self.historyQueue, ^{
        NSMutableArray *historyArray = [NSMutableArray array];
        
        for (DMLifecycleStateHistoryItem *item in self.stateHistory) {
            NSDictionary *itemDict = @{
                @"state": DMLifecycleStateDescription(item.state),
                @"stateValue": @(item.state),
                @"triggerEvent": DMLifecycleEventDescription(item.triggerEvent),
                @"triggerEventValue": @(item.triggerEvent),
                @"timestamp": @([item.timestamp timeIntervalSince1970]),
                @"duration": @(item.duration)
            };
            [historyArray addObject:itemDict];
        }
        
        NSDictionary *exportData = @{
            @"exportTime": @([[NSDate date] timeIntervalSince1970]),
            @"currentState": DMLifecycleStateDescription(self.currentState),
            @"currentStateValue": @(self.currentState),
            @"historyCount": @(historyArray.count),
            @"history": historyArray
        };
        
        NSError *error = nil;
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:exportData
                                                           options:NSJSONWritingPrettyPrinted
                                                             error:&error];
        
        if (jsonData && !error) {
            jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        } else {
            NSLog(@"[DMLifecycleStateManager] Failed to export state history as JSON: %@", error.localizedDescription);
        }
    });
    
    return jsonString;
}

@end